import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import path from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
// https://vite.dev/config/
import { viteMockServe } from 'vite-plugin-mock'

export default defineConfig(({ mode }) => {
  //获取环境变量
  let env = loadEnv(mode, process.cwd())
  console.log('环境变量:', env) // 添加这行查看变量
  return {
    plugins: [
      vue(),
      VueSetupExtend(),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        symbolId: 'icon-[dir]-[name]',
      }),
      viteMockServe({
        // localEnabled: command === 'serve', //开发阶段可以使用mock接口
      }),
    ],
    base: '/glzx/',
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'), // 相对路径别名配置，使用 @ 代替 src
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: '@use "@/styles/variable.scss" as *; ',
        },
      },
    },
    server: {
      proxy: {
        [env.VITE_APP_BASE_API]: {
          //获取服务器地址
          target: env.VITE_SERVER,
          //需要代理跨域
          changeOrigin: true,
          //路径重写
          rewrite: (path) => {
            console.log('原始路径:', path)
            const newPath = path.replace(
              new RegExp('^' + env.VITE_APP_BASE_API),
              '',
            )
            console.log('重写后路径:', newPath)
            return newPath
          },
        },
      },
    },
  }
})
